package data_generator.xml;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import data_generator.entity.NodeLocation;
import data_generator.entity.SensorNode;
import data_generator.entity.Temperature;

public class XMLConfig {
	public static Map<SensorNode, ArrayList<Temperature>> nodeMap;
	private static Map<SensorNode, Temperature> nodeTempMap;
	@SuppressWarnings("rawtypes")
	public static Map loadConfig(String fileName){
		if(fileName == null || fileName.trim().equals("")){
			fileName = "nodelist.xml";
		}
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(fileName);
			Element rootElement = doc.getRootElement();
			List nodes = rootElement.elements("Node");
			Iterator it = nodes.iterator();
			nodeMap = new LinkedHashMap<SensorNode, ArrayList<Temperature>>();
			while (it.hasNext()) {
				Element nodeElement = (Element)it.next();
				SensorNode sn = new SensorNode();
				sn.setId(nodeElement.elementText("id"));
				sn.setName(nodeElement.elementText("name"));
				Element locationElement = nodeElement.element("location"); 
				NodeLocation nl = new NodeLocation(
						Integer.parseInt(locationElement.elementText("x")), 
						Integer.parseInt(locationElement.elementText("y")),
						Integer.parseInt(locationElement.elementText("z")));
				sn.setLocation(nl);
				Element data = nodeElement.element("data");
				List tempList = data.elements("temperature");
				Iterator itTemp = tempList.iterator();
				ArrayList<Temperature> tempArrayList = new ArrayList<Temperature>();
				while(itTemp.hasNext()){
					Element tempElement = (Element)itTemp.next();
					Temperature t = new Temperature(
							tempElement.attributeValue("time"), 
							Float.parseFloat(tempElement.getStringValue()));
					tempArrayList.add(t);
					
				}
				nodeMap.put(sn, tempArrayList);
				
			}
		} catch (DocumentException e) {
			
			e.printStackTrace();
		}
		System.out.println(nodeMap.size());
		return nodeMap;
	}
	
	public static Map<SensorNode, Temperature> getNodeTemperatureByPos(int pos){
		try {
			nodeTempMap = new LinkedHashMap<SensorNode, Temperature>();
			@SuppressWarnings("rawtypes")
			Iterator iterator = XMLConfig.nodeMap.keySet().iterator();
			while (iterator.hasNext()) {

				SensorNode sn = (SensorNode) iterator.next();
				if (sn.isShow()) {
					ArrayList<Temperature> tempList = (ArrayList<Temperature>) XMLConfig.nodeMap
							.get(sn);
					Temperature temp = tempList.get(pos);
					nodeTempMap.put(sn, temp);
				}
			}
		} catch (Exception e) {
			System.out.println("out of bound");
		}

		return nodeTempMap;
	}
	@SuppressWarnings("rawtypes")
	public static Map loadConfig(){
		return loadConfig(null);
	}
}
